package com.bocloud.paas.s2i.service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.bocloud.paas.s2i.util.ExecuteCommandUtil;
import com.bocloud.paas.s2i.util.Result;

/**
 * s2i服务类
 * 
 * @author zjm
 *
 */
@Service("STIService")
public class STIServiceImpl {

	private static final Logger logger = LoggerFactory.getLogger(STIServiceImpl.class);
	/**
	 * s2i存放结果文件主路径
	 */
	private static final String STI_HOME = "/opt/s2i_home/";
	/**
	 * s2i存放脚本文件主路径
	 */
	private static final String STI_SHELL = "/opt/s2i_shell/";
	/**
	 * s2i构建脚本的文件名
	 */
	private static final String BUILD_SH_NAME = "build.sh";

	/**
	 * 构建s2i镜像
	 * 
	 * @param baseImage
	 *            基础镜像名称
	 * @param pomPath
	 *            pom文件的位置
	 * @param repositoryUrl
	 *            代码仓库地址
	 * @param repositoryBranch
	 *            代码仓库分支，默认master
	 * @param repositoryUsername
	 *            代码仓库用户名
	 * @param repositoryPassword
	 *            代码仓库密码
	 * @param warName
	 *            war包名称
	 * @param newImage
	 *            构建后的镜像名称
	 * @param registryUrl
	 *            镜像仓库url（包含端口号）
	 * @param registryUsername
	 *            镜像仓库账户
	 * @param registryPassword
	 *            镜像仓库密码
	 * 
	 */
	public Result build(String baseImage, String pomPath, String repositoryUrl, String repositoryBranch,
			String repositoryUsername, String repositoryPassword, String warName, String newImage, String registryUrl,
			String registryUsername, String registryPassword) {
		Result result = new Result();
		// 判断参数格式
		if (StringUtils.isBlank(baseImage) || StringUtils.isBlank(pomPath) || StringUtils.isBlank(repositoryUrl)
				|| StringUtils.isBlank(repositoryBranch) || StringUtils.isBlank(warName)
				|| StringUtils.isBlank(newImage) || StringUtils.isBlank(registryUrl)) {
			result.setMessage("param format error!");
			logger.error(result.getMessage());
			return result;
		}
		registryUsername = registryUsername == null ? "" : registryUsername;
		registryPassword = registryPassword == null ? "" : registryPassword;

		String shPath = STI_SHELL + BUILD_SH_NAME;
		String sourceUrl = repositoryUrl;
		if (StringUtils.isNotBlank(repositoryUsername) && StringUtils.isNotBlank(repositoryPassword)
				&& repositoryUrl.indexOf("http") > -1) {
			// 转义源码的用户名密码的特殊字符
			try {
				repositoryUsername = URLEncoder.encode(repositoryUsername, "utf-8");
				repositoryPassword = URLEncoder.encode(repositoryPassword, "utf-8");
			} catch (UnsupportedEncodingException e) {
				result.setMessage("convert [" + repositoryUsername + "] or [" + repositoryPassword + "] fail!");
				logger.error(result.getMessage() + " \n", e);
				return result;
			}

			// TODO 拼接源码地址账户密码和地址，待优化
			sourceUrl = repositoryUrl.substring(0, repositoryUrl.indexOf("//") + 2) + repositoryUsername + ":"
					+ repositoryPassword + "@" + repositoryUrl.substring(repositoryUrl.indexOf("//") + 2);
		}

		String[] command = { "sh", shPath, warName, pomPath, sourceUrl, baseImage, newImage, repositoryBranch,
				registryUrl, registryUsername, registryPassword };
		// 设置存储构建记录的文件名
		while (newImage.lastIndexOf("/") > 0) {
			newImage = newImage.substring(newImage.lastIndexOf("/") + 1);
		}
		newImage = newImage.lastIndexOf(":") > 0 ? newImage.replace(":", "_") : newImage;
		String fileName = newImage + "-" + Long.toString(System.currentTimeMillis() / 1000);
		fileName = STI_HOME + "build/" + fileName;

		result = ExecuteCommandUtil.exec(command, fileName);
		if (result.getCode() == 0) {
			result.setSuccess(true);
			result.setMessage(
					"execute s2i build image [" + newImage + "] success! The result is saved in [" + fileName + "] ");
			logger.info("——————————————————————————————————> " + result.getMessage());
		} else {
			result.setMessage(
					"execute s2i build image [" + newImage + "] fail!! The result is saved in [" + fileName + "] ");
			logger.error("——————————————————————————————————> " + result.getMessage());
		}
		return result;
	}

}
